package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WBG.xiaohu
 * @since 2025-4-21
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 1.根据id查询店铺信息
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        //缓存穿透
        // shop = getShopById(id);

        //互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 使用互斥锁查询商店信息
     *
     * @param id 商店ID
     * @return 商店对象，如果不存在则返回null
     */
    private Shop queryWithMutex(Long id) {
        //1.从redis中查询
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断是否为空
        if (shopJson != null) {
            return null;
        }

        //4.实现缓存重建
        //4.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = lock(lockKey);
            //4.2 判断是否获取成功
            if (!isLock) {
                //4.4 失败，重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //4.3 成功，根据id查询数据库
            log.info("查询数据库，id为：{}", id);
            shop = getById(id);

            //5.数据库不存在，返回错误
            if (shop == null) {
                //把空值写入redis
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", 2, TimeUnit.MINUTES);
                return null;
            }
            //6.存在，写入redis
            String jsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr, 30, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7.释放互斥锁
            unLock(lockKey);
        }

        return shop;
    }

    private boolean lock(String key) {
        //上锁
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unLock(String key) {
        //删除锁
        stringRedisTemplate.delete(key);
    }

    private Shop getShopById(Long id) {
        //1.从redis中查询
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //TODO判断是否为空
        if (shopJson == null) {
            return null;
        }
        //4.不存在，根据id查询数据库
        Shop shop = getById(id);
        //5.数据库不存在，返回错误
        if (shop == null) {
            //把空值写入redis
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", 2, TimeUnit.MINUTES);
            return null;
        }
        //6.存在，写入redis
        String jsonStr = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr, 30, TimeUnit.MINUTES);

        return shop;
    }

    /**
     * 2.更新店铺信息
     *
     * @param shop 待更新的店铺对象，必须包含有效的店铺ID
     * @return 返回更新操作的结果
     */
    // 使用事务管理，确保方法执行过程中出现异常时回滚事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result update(Shop shop) {
        // 检查店铺对象的ID是否为空，为空则返回错误提示
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        // 调用MyBatis-Plus的方法，根据ID更新店铺信息
        updateById(shop);
        // 更新完成后，删除Redis中对应的店铺缓存，确保数据一致性
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        return Result.ok();
    }
}
